单例
唯一的实例,即整个 java 系统中某个类型的对象只有唯一的一个。
无论是饿汉式还是懒汉式的单例,写法都有以下步骤:
- 类的构造器私有化(保证使用者不能随意创建第二个对象)
- 唯一的实例必须在本类中创建,并且要用一个静态的变量来存储。
饿汉式
无论使用者是否要用这个对象,都会先创建这个对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package com.itguigu.singleton;
public class TestHungry { public static void main(String[] args) { Hungry instance = Hungry.instance; Hungry2 instance2 = Hungry2.instance; Hungry3 instance3 = Hungry3.getInstance(); } }
class Hungry{ public static final Hungry instance = new Hungry(); private Hungry() { } }
enum Hungry2{ instance }
class Hungry3{ private static final Hungry3 instance = new Hungry3(); private Hungry3() { } public static Hungry3 getInstance() { return instance; } }
|
懒汉式
只有在使用者在来获取这个对象时,才会创建对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package com.itguigu.singleton;
public class TestLazy { Lazy instance = Lazy.getInstance(); Lazy2 instance2 = Lazy2.getInstance(); Lazy3 instance3 = Lazy3.getInstance(); }
class Lazy{ private static Lazy instance; private Lazy() { } public synchronized static Lazy getInstance() { if(instance==null) { instance = new Lazy(); } return instance; } }
class Lazy2{ private static Lazy2 instance; private Lazy2() { } public synchronized static Lazy2 getInstance() { if (instance==null) { synchronized (Lazy2.class) { if(instance==null) { instance = new Lazy2(); } } } return instance; } }
class Lazy3{ private Lazy3() { } private static class Inner{ private static final Lazy3 instance = new Lazy3(); } public static Lazy3 getInstance() { return Inner.instance; } }
|
网络概述
InetAddress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.itguigu.singleton;
import java.net.InetAddress; import java.net.UnknownHostException;
import org.junit.Test;
public class TestInetAddress { @Test public void name() throws UnknownHostException { InetAddress localHost = InetAddress.getLocalHost(); System.out.println(localHost); String hostName = localHost.getHostName(); String hostAddress = localHost.getHostAddress(); System.out.println("名称:" + hostName + "地址:" + hostAddress); } @Test public void name1() throws UnknownHostException { InetAddress byName = InetAddress.getByName("www.baidu.com"); System.out.println(byName); } }
|